//
//  WBEmoticonCollectionView.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/25.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit

private let WBEmoticonCollectionViewCellID = "WBEmoticonCollectionViewCellID"

class WBEmoticonCollectionView: UICollectionView {


    // MARK: -  重写init方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setUpUI()
    }

    // MARK: -  重写init方法时必须要实现的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -  设置UI
    func setUpUI() {
        
        registerClass(WBEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: WBEmoticonCollectionViewCellID)
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: kScreenW, height: 216 - 37)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal
        
        self.showsHorizontalScrollIndicator = false
        self.bounces = false
        self.pagingEnabled = true
        
        delegate = self
        dataSource = self
    }

}

// MARK: -  CollectionView的数据源和代理方法
extension WBEmoticonCollectionView: UICollectionViewDelegate, UICollectionViewDataSource {
    
    
    // MARK: -  设置item的样子
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = self.dequeueReusableCellWithReuseIdentifier(WBEmoticonCollectionViewCellID, forIndexPath: indexPath) as! WBEmoticonCollectionViewCell
        cell.indexPath = indexPath
        cell.emoticons = WBEmoticonTool.sharedTools.allEmoticons[indexPath.section][indexPath.row]
        return cell
    }
    
    // MARK: -  返回item个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        return WBEmoticonTool.sharedTools.allEmoticons[section].count
    }
    
    // MARK: -  返回组数
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return WBEmoticonTool.sharedTools.allEmoticons.count
    }
}



// MARK: -  自定义collectionviewcell
class WBEmoticonCollectionViewCell: UICollectionViewCell {
    
    
    // MARK: -  表情一维数组
    var emoticons: [WBEmoticonModel]? {
        
        didSet {
            
            for button in buttons {
                
                button.hidden = true
            }
            for (i, emoticon) in emoticons!.enumerate(){
                
                let button = buttons[i]
                button.hidden = false
                button.emoticonModel = emoticon
                
                if emoticon.isEmoji {
                    
                    button.setTitle(((emoticon.code ?? "") as NSString).emoji(), forState: UIControlState.Normal)
                    
                    //解决cell重用问题
                    button.setImage(nil, forState: UIControlState.Normal)
                }else {
      
                    let path = "\(emoticon.path!)\(emoticon.png!)"
                    let image = UIImage(named: path, inBundle: WBEmoticonTool.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
                    button.setImage(image, forState: UIControlState.Normal)
                    
                    //解决cell重用问题
                    button.setTitle("", forState: UIControlState.Normal)
                }
            }
        }
    }
    
    
    // MARK: -  保存表情按钮数组
    var buttons: [WBEmoticonButton] = [WBEmoticonButton]()
    
    // MARK: -  indexpath属性
    var indexPath: NSIndexPath? {
        
        didSet {
            
//            showLabel.text = "第\(indexPath!.section)组第\(indexPath!.item)页"
        }
    }
    
    // MARK: -  重写init方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setUpUI()
    }

    // MARK: -  重写init方法时必须要实现的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -  设置视图
    private func setUpUI() {
        
        self.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        createButtons()
        contentView.addSubview(deleteButton)
        
    }
    
    // MARK: -  设置表情button的frame
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let buttonW = (kScreenW - 10) / CGFloat(WBEmoticonMaxColum)
        let buttonH = (216 - 37 - 20) / CGFloat(WBEmoticonMaxRaw)
        
        //遍历数组
        for (i, button) in buttons.enumerate() {
            
            let currentColum = i % WBEmoticonMaxColum
            let currentRaw = i / WBEmoticonMaxColum
            
            button.frame = CGRect(x: CGFloat(currentColum) * buttonW + 5, y: CGFloat(currentRaw) * buttonH, width: buttonW, height: buttonH)
            
        }
        
        deleteButton.frame = CGRect(x: kScreenW - 5 - buttonW, y: buttonH * 2, width: buttonW, height: buttonH)
    }
    
    // MARK: -  创建表情button抽取出来的方法
    func createButtons() {
        
        for _ in 0..<WBEmoticonMaxCount {
            
            let button = WBEmoticonButton()
            button.addTarget(self, action: "clickEmoticonButton:", forControlEvents: UIControlEvents.TouchUpInside)
            button.titleLabel?.font = UIFont.systemFontOfSize(32)
            contentView.addSubview(button)
            buttons.append(button)
        }
        
    }
    
    // MARK: -  表情按钮的点击事件
    func clickEmoticonButton(button: WBEmoticonButton) {
        print("11111111111111111111")
        NSNotificationCenter.defaultCenter().postNotificationName(emoticonButtonWasClickedNotification, object: button.emoticonModel)
    }
    
    // MARK: -  删除按钮的点击事件
    func clickDeleteButton() {
        
        NSNotificationCenter.defaultCenter().postNotificationName(deleteButtonWasClickedNotification, object: nil)
    }
    
    // MARK: -  懒加载删除按钮
    private lazy var deleteButton: UIButton = {
       
        let button = UIButton()
        button.addTarget(self, action: "clickDeleteButton", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        return button
        
    }()
    
    // MARK: -  懒加载控件
    private lazy var showLabel: UILabel = {
        
        let showLabel = UILabel()
        showLabel.textColor = UIColor.redColor()
        showLabel.font = UIFont.systemFontOfSize(20)
        showLabel.backgroundColor = UIColor.yellowColor()
        showLabel.numberOfLines = 0
        showLabel.textAlignment = .Center
        return showLabel
    }()
}